package com.cl.code.common.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class ResourceFileUtils {

    /**
     * 读取文件
     *
     * @param pathname 文件路径
     * @return 文件
     */
    public static File readFile(String pathname) throws IOException {
        URL systemResource = ClassLoader.getSystemResource(pathname);
        if (systemResource == null) {
            throw new IOException("file not found");
        } else {
            try {
                return new File(systemResource.toURI());
            } catch (URISyntaxException e) {
                throw new IOException(e);
            }
        }
    }

    /**
     * 读取文件内容
     *
     * @param pathname 文件路径
     * @return 文件内容
     * @throws IOException 读取异常
     */
    public static String readFileContent(String pathname) throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream(pathname);
        if (inputStream == null) {
            throw new IOException("file not found");
        }
        return readFileContent(inputStream);
    }

    /**
     * 读取文件内容
     *
     * @param file 文件
     * @return 文件内容
     * @throws IOException 读取异常
     */
    public static String readFileContent(File file) throws IOException {
        return readFileContent(Files.newInputStream(file.toPath()));
    }

    /**
     * 读取文件内容
     *
     * @param is 输入流
     * @return 文件内容
     * @throws IOException 读取异常
     */
    public static String readFileContent(InputStream is) throws IOException {
        try (ReadableByteChannel channel = Channels.newChannel(is)) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            StringBuilder sb = new StringBuilder();
            while (channel.read(buffer) != -1) {
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                sb.append(new String(bytes));
                buffer.clear();
            }
            return sb.toString();
        }
    }

}
